<?php
namespace Wanecho\Mobilelogin\Api\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Flarum\Settings\SettingsRepositoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Laminas\Diactoros\Response\JsonResponse;
use Flarum\User\User;
use Illuminate\Support\Arr;
use Flarum\User\UserRepository;
use Wanecho\Mobilelogin\Api\WanechoSms;
use Flarum\Http\RequestUtil;

class ChangePwdController implements RequestHandlerInterface
{

    /**
     * @var SettingsRepositoryInterface
     */
    protected $users;
    
    protected $valid_period = 30 * 3; // sms timeout 3 minute

    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }

    public function handle(ServerRequestInterface $request): Response
    {
        
        $body = $request->getParsedBody();
        $code = (int) Arr::get($body, 'code');
        $password = Arr::get($body, 'pwd');
        if ($password == '') {
            return new JsonResponse('请输入密码', 500);
        }
        if ($code == '') {
            return new JsonResponse('请输入短信验证码', 500);
        }
        $actor = RequestUtil::getActor($request);
        // //检测原手机号是否正确
        // $user = User::where(['mobile' => $oldmobile,'id'=>$actor->id])->first();
        // if(!$user){
        //     return new JsonResponse('原手机号错误', 500);
        // }
        //检测发送记录
        $sms_response = WanechoSms::where([
            'mobile' => $actor->mobile,
            'user_id' => $actor->id,
            // 'code' => $code,
            'is_active' => 0
        ])->orderBy('id', 'desc')->first();
        if (!$sms_response) {
            return new JsonResponse('请先发送验证码', 500);
        }
        //检测验证码
        if ((int) $sms_response->code !== $code) {
            return new JsonResponse('短信验证码错误', 500);
        }
        $sms_response->is_active = 1;
        $sms_response->save();
        if ($sms_response->created_at > date('Y-m-d H:i:s', time() + $this->valid_period)) {
            return new JsonResponse('验证码已过期，请重新获取', 500);
        }
        // //检测手机号是否绑定
        // $user = User::where(['mobile' => $phone])->first();
        // if($user){
        //     return new JsonResponse('该手机号已绑定', 500);
        // }
        //修改手机号
        $user = User::where(['id' => $actor->id])->first();
        $user->changePassword($password);
        if($user->save()){
            return new JsonResponse('修改成功', 200);
        }else{
            return new JsonResponse('修改失败', 500);
        }

    }

}